package com.example.boardroom.newItems;

import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.bigkoo.pickerview.view.TimePickerView;
import com.blankj.utilcode.util.GsonUtils;
import com.blankj.utilcode.util.LogUtils;
import com.blankj.utilcode.util.TimeUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.entity.node.BaseNode;
import com.chad.library.adapter.base.listener.OnItemLongClickListener;
import com.example.boardroom.R;
import com.example.boardroom.demo.BaseActivity;
import com.example.boardroom.demo.Content;
import com.example.boardroom.demo.room.AppDatabase;
import com.example.boardroom.demo.room.HardwareControlDao;
import com.example.boardroom.demo.room.HardwareControlTable;
import com.example.boardroom.demo.times.EventTimes;
import com.github.florent37.singledateandtimepicker.SingleDateAndTimePicker;
import com.github.florent37.singledateandtimepicker.dialog.DoubleDateAndTimePickerDialog;
import com.github.florent37.singledateandtimepicker.dialog.SingleDateAndTimePickerDialog;
import com.lxj.xpopup.XPopup;
import com.lxj.xpopup.core.BasePopupView;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.callback.StringCallback;
import com.lzy.okgo.model.Response;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.json.JSONException;
import org.json.JSONObject;

import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.TimeZone;
import java.util.concurrent.TimeUnit;

import cn.nodemedia.NodePlayer;
import cn.nodemedia.NodePlayerDelegate;
import cn.nodemedia.NodePlayerView;

/**
 * 灯      接入
 * 窗帘
 * 门禁
 * 空调
 * 新风
 * 电表
 * 传感器    接入
 */
public class HardwareControlActivity extends BaseActivity {
    private NodePlayer nodePlayer = null;
    NodePlayerView view_video;
    private NodeAdapter adapter;
    private RecyclerView recyclerview;
    TextView tc_humidity, tc_pm, tc_illuminance, tv_accessControl;
    private Button btn_tv_open, btn_tv_close, btn_openTheAccessControl, btn_queryData;
    HardwareControlDao dao;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        dao = AppDatabase.getInstance(this).hardwareControlDao();
        setContentView(R.layout.activity_hard);
        EventBus.getDefault().register(this);
        recyclerview = findViewById(R.id.recyclerview);
        view_video = findViewById(R.id.view_video);
        tc_humidity = findViewById(R.id.tc_humidity);
        tc_illuminance = findViewById(R.id.tc_illuminance);
        btn_tv_open = findViewById(R.id.btn_tv_open);
        btn_tv_close = findViewById(R.id.btn_tv_close);
        btn_queryData = findViewById(R.id.btn_queryData);
        tc_pm = findViewById(R.id.tc_pm);
        tv_accessControl = findViewById(R.id.tv_accessControl);
        btn_openTheAccessControl = findViewById(R.id.btn_openTheAccessControl);
        startPlaySteam("rtsp://admin:kyo12345@192.168.1.57:554/h264/ch1/main/av_streamadmin192168157");
        getHardwareList();
        initAdapter();
        getHumidity();
        getIllumination();
        btn_tv_open.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                switchTVOnAndOff(true);
            }
        });
        btn_tv_close.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                switchTVOnAndOff(false);
            }
        });
        btn_openTheAccessControl.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                openTheAccessControl();
            }
        });
        btn_queryData.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        Integer rowCount = dao.getRowCount();
                        ToastUtils.showLong(rowCount + "条数据");
                    }
                }).start();

            }
        });
        btn_openTheAccessControl.setOnLongClickListener(new View.OnLongClickListener() {
            @Override
            public boolean onLongClick(View v) {
                ToastUtils.showLong("消耗了长按事件");
                return true;
            }
        });
        initPop();
        initTime();
    }


    private void startPlaySteam(String address) {
        nodePlayer = new NodePlayer(HardwareControlActivity.this, "M2FmZTEzMGUwMC00ZTRkNTMyMS1jbi5ub2RlbWVkaWEucWxpdmU=-OTv6MJuhXZKNyWWMkdKJWsVKmLHwWPcPfnRbbWGIIf+8t39TqL/mW2f5O5WdT/W8JJE7ePvkvKaS371xVckAZ/U00dSwPp8ShB8Yic2W1GhwCyq04DYETsrGnkOWrhARH7nzNhd3Eq6sVC1Fr74GCEUHbDSCZnCfhcEnzGU9InRiQJ2PImtHORahN3blAGlHb6LZmdnobw5odvKEeUhbkhxYf8S1Fv4VRnSpDCSS3LZ2U3Mp6MfGDA1ZXPadmgdwaJitIrnWA2zP/yqmlUHjMtTv8PzGcc73Tm5k5q+OMbKCJsPq8KSEpFthncvaGZJ2kS2GHx6V5TqYZglBrTx61g==");
        nodePlayer.setNodePlayerDelegate(new NodePlayerDelegate() {
            @Override
            public void onEventCallback(NodePlayer player, int event, String msg) {

            }
        });
        nodePlayer.setPlayerView(view_video);
        nodePlayer.setAudioEnable(true);

        /**
         * 设置播放直播视频url
         */
        nodePlayer.setInputUrl(address);

        /**
         * 设置启动缓冲区时长,单位毫秒.此参数关系视频流连接成功开始获取数据后缓冲区存在多少毫秒后开始播放
         */
        nodePlayer.setBufferTime(300);

        /**
         * 设置最大缓冲区时长,单位毫秒.此参数关系视频最大缓冲时长.
         * RTMP基于TCP协议不丢包,网络抖动且缓冲区播完,之后仍然会接受到抖动期的过期数据包.
         * 设置改参数,sdk内部会自动清理超出部分的数据包以保证不会存在累计延迟,始终与直播时间线保持最大maxBufferTime的延迟
         */
        nodePlayer.setMaxBufferTime(1000);

        /**
         *
         开启硬件解码,支持4.3以上系统,初始化失败自动切为软件解码,默认开启.
         */
        nodePlayer.setHWEnable(true);

        /**
         * 设置连接超时时长,单位毫秒.默认为0 一直等待.
         * 连接部分RTMP服务器,握手并连接成功后,当播放一个不存在的流地址时,会一直等待下去.
         * 如需超时,设置该值.超时后返回1006状态码.
         */
        // np.setConnectWaitTimeout(10*1000);

        /**
         * @brief rtmpdump 风格的connect参数
         * Append arbitrary AMF data to the Connect message. The type must be B for Boolean, N for number, S for string, O for object, or Z for null.
         * For Booleans the data must be either 0 or 1 for FALSE or TRUE, respectively. Likewise for Objects the data must be 0 or 1 to end or begin an object, respectively.
         * Data items in subobjects may be named, by prefixing the type with 'N' and specifying the name before the value, e.g. NB:myFlag:1.
         * This option may be used multiple times to construct arbitrary AMF sequences. E.g.
         */
        // np.setConnArgs("S:info O:1 NS:uid:10012 NB:vip:1 NN:num:209.12 O:0");

        /**
         * 设置RTSP使用TCP传输模式
         * 支持的模式有:
         * NodePlayer.RTSP_TRANSPORT_UDP
         * NodePlayer.RTSP_TRANSPORT_TCP
         * NodePlayer.RTSP_TRANSPORT_UDP_MULTICAST
         * NodePlayer.RTSP_TRANSPORT_HTTP
         */
        nodePlayer.setRtspTransport(NodePlayer.RTSP_TRANSPORT_TCP);

        nodePlayer.setCryptoKey("");

        nodePlayer.start();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        recover();
        EventBus.getDefault().unregister(this);
    }

    /**
     * 回收流播放器
     */
    private void recover() {
        if (null != nodePlayer) {
            nodePlayer.stop();
            nodePlayer.release();
        }
    }

    private void initAdapter() {
//        recyclerview.setLayoutManager(new LinearLayoutManager(this));
        recyclerview.setLayoutManager(new GridLayoutManager(this, 2));
        adapter = new NodeAdapter();
        recyclerview.setAdapter(adapter);
//        adapter.setOnItemClickListener(new OnItemClickListener() {
//            @Override
//            public void onItemClick(@NonNull BaseQuickAdapter<?, ?> adapter, @NonNull View view, int position) {
//                // 查找某位置Node的 父节点
//                int parentNode = Objects.requireNonNull(adapter).findParentNode(position);
//                LogUtils.i("lufei_node","当前父节点:"+parentNode+"");
//                ToastUtils.showLong(position+"子节点");
//            }
//        });
        adapter.setOnItemLongClickListener(new OnItemLongClickListener() {
            @Override
            public boolean onItemLongClick(@NonNull BaseQuickAdapter<?, ?> adapter, @NonNull View view, int position) {
                FirstNode node = (FirstNode) adapter.getData().get(position);
                if (node.dataDTO.deviceType.equals("access_control")) {
                    getAccessControlTimeList(node.dataDTO.id, 0, 1, 10);
                } else {
                    queryDataBase(node.dataDTO.id);
                    popupView.show();
//                    new RoomUtils(HardwareControlActivity.this).queryDataBase(node.dataDTO.id);
                }
                return true;
            }
        });
    }

    /**
     * 获取硬件列表
     */
    private void getHardwareList() {
        showLoadingView(false, "加载数据中...");

        OkGo.<String>get(Content.baseUrl + "applet/device/queryDevicesInfosByArea?areaId=4")
                .tag(this)
                .execute(new StringCallback() {
                    @Override
                    public void onSuccess(Response<String> response) {
                        LogUtils.i("lufei_response11", response.toString(), response.body());
                        HardBean hardBean = GsonUtils.fromJson(response.body(), HardBean.class);
                        storedInTheDatabase(hardBean);
                        adapter.setList(upData(hardBean));

                    }

                    @Override
                    public void onFinish() {
                        super.onFinish();
                        hideLoadingView();
                    }
                });
    }

    private List<BaseNode> upData(HardBean response) {
        List<BaseNode> list = new ArrayList<>();
        List<BaseNode> sss;
        for (HardBean.DataDTO datum : response.data) {
            sss = new ArrayList<>();
            if (datum.deviceType.equals("aircondition_control")) {
                sss.add(new SecondNode("1", "1档"));
                sss.add(new SecondNode("1", "2档"));
                sss.add(new SecondNode("1", "3档"));
                sss.add(new SecondNode("2", "关闭"));
            } else if (datum.deviceType.equals("curtain_control")) {
                sss.add(new SecondNode("1", "升"));
                sss.add(new SecondNode("2", "降"));
            } else if (datum.deviceType.equals("light_control")) {
                sss.add(new SecondNode("1", "开"));
                sss.add(new SecondNode("2", "关"));
            } else if (datum.deviceType.equals("touch_terminal")) {
                sss.add(new SecondNode("1", "开"));
                sss.add(new SecondNode("2", "关"));
            } else if (datum.deviceType.equals("access_control")) {
                sss.add(new SecondNode("1", "开"));
            }

            list.add(new FirstNode(datum, sss));
        }
        return list;
    }

    /**
     * {
     * "msg": "操作成功",
     * "code": 200,
     * "data": {
     * "pm2.5": "44.0",
     * "pm10": "58.0",
     * "humidity": "30.7"
     * }
     * }
     */
    private void getHumidity() {
        OkGo.<String>get(Content.baseUrl + "link/device/getAreaEnMessage/4")
                .tag(this)
                .execute(new StringCallback() {
                    @Override
                    public void onSuccess(Response<String> response) {
                        LogUtils.i("lufe_getHumidity", response.body());
                        try {
                            JSONObject jsonObject = new JSONObject(response.body());

                            JSONObject data = jsonObject.optJSONObject("data");
                            if (data != null) {
                                String pm = data.getString("pm2.5");
                                long humidity = data.getLong("humidity");
                                LogUtils.i("lufe_getHumidity", pm, humidity);
                                DecimalFormat format = new DecimalFormat("#.##");
                                String numberStr = format.format(humidity);
                                Log.e("TAG", "numberStr => " + numberStr);
                                tc_humidity.setText(String.format("温度: %s°", numberStr));
                                tc_pm.setText(String.format("pm2.5: %s％", pm));
                            }

                        } catch (JSONException e) {
                            e.printStackTrace();
                        }

                    }
                });
    }

    /**
     * 开关电视
     */
    private void switchTVOnAndOff(boolean IsSwitch) {
        OkGo.<String>post(Content.baseUrl + "link/device/switchScreen?switch=" + IsSwitch)
                .tag(this)
                .execute(new StringCallback() {
                    @Override
                    public void onSuccess(Response<String> response) {

                    }
                });
    }


    /**
     * 获取光照度
     */
    private void getIllumination() {
        OkGo.<String>get(Content.baseUrl + "link/device/singleReadAreaDevice?areaId=30&deviceType=light_sense&switchStatus=7")
                .tag(this)
                .execute(new StringCallback() {
                    @Override
                    public void onSuccess(Response<String> response) {
                        tc_illuminance.setText("光照度: " + response.body());
                    }
                });
    }

    /**
     * 开启门禁
     */
    public void openTheAccessControl() {
        OkGo.<String>post(Content.baseUrl + "deviceMonitor/yjDevice/openDoor")
                .tag(this)
                .execute(new StringCallback() {
                    @Override
                    public void onSuccess(Response<String> response) {
                        AccessControlBean bean = GsonUtils.fromJson(response.body(), AccessControlBean.class);
                        ToastUtils.showShort(bean.data.msg);
                    }
                });

    }

    /**
     * 设备列表存入数据库
     */
    private void storedInTheDatabase(HardBean hardBean) {

        new Thread(new Runnable() {
            @Override
            public void run() {
                for (HardBean.DataDTO datum : hardBean.data) {
                    //处理掉空调的特殊字段
                    if (datum.deviceType.equals("aircondition_control") && !datum.openStatus.equals("2")) {
                        datum.openStatus = "1";
                        dao.insertAll(new HardwareControlTable(TimeUtils.getNowString(), datum));
                    } else {
                        dao.insertAll(new HardwareControlTable(TimeUtils.getNowString(), datum));
                    }

                }

            }
        }).start();

    }

    /**
     * 查询数据库
     */
    private void queryDataBase(int id) {
        new Thread(new Runnable() {
            @Override
            public void run() {
                List<HardwareControlTable> tables = dao.getDevicesById2(id);
                for (HardwareControlTable table : tables) {
                    LogUtils.i("lufei_table", table.openStatus);
                }
                extractValidData(tables);
            }
        }).start();
    }

    String oldOpenStatus = "2";

    /**
     * 提取有效数据
     */
    private void extractValidData(List<HardwareControlTable> tables) {
        List<HardwareControlTable> list = new ArrayList<>();
        for (HardwareControlTable table : tables) {
            if (!table.openStatus.equals(oldOpenStatus)) {
                list.add(table);
            }
            oldOpenStatus = table.openStatus;
        }
        List<QueryTimeStamp> stampList = new ArrayList<>();
        if (list.size() > 1) {
            for (int i = 0; i < list.size(); i++) {
                if (list.get(i).openStatus.equals("2")) {
                    if (i != 0) {
                        stampList.add(new QueryTimeStamp(list.get(i - 1), list.get(i)));
                    }

                }
                LogUtils.i("lufei_table2", list.get(i).openStatus);
            }
        }

        //最后一个状态处理
        if (list.size() > 0) {
            HardwareControlTable hardwareControlTable = list.get(list.size() - 1);
            if (hardwareControlTable.openStatus.equals("1")) {
                stampList.add(new QueryTimeStamp(hardwareControlTable, hardwareControlTable));
            }
        }

//        popupView.show();

        //                List<DAM3200Table> threeTimeDatas = dam3200Dao.getThreeTimeDatas(DateUtils.beforeOneHourToNowDate(3), TimeUtils.getNowString());
        EventBus.getDefault().postSticky(new EventTimes(stampList, 2));
        for (QueryTimeStamp queryTimeStamp : stampList) {
            LogUtils.i("lufei_table3", queryTimeStamp + "-----" + queryTimeStamp, stampList, stampList.size());
        }

    }

    BasePopupView popupView;

    private void initPop() {

        CustomPopup customPopup = new CustomPopup(this);
        customPopup.setOnClickListenerCUs(new CustomPopup.OnClickListenerCUs() {
            @Override
            public void onClickCUs(View v) {


            }
        });
        popupView = new XPopup.Builder(this)

                .autoOpenSoftInput(false)
                .asCustom(customPopup);

    }

    @Subscribe(sticky = true, threadMode = ThreadMode.MAIN)
    public void getEvent(EventTimes event) {
        if (event.type == 3) {
            getHardwareList();
        }

    }

    /**
     * 获取门禁时间列表
     */
    private void getAccessControlTimeList(int deviceId, int handleType, int pageNum, int pageSize) {
        HashMap<String, Object> hashMap = new HashMap<>();
        hashMap.put("deviceId", deviceId);
        hashMap.put("handleType", handleType);
        hashMap.put("pageNum", pageNum);
        hashMap.put("pageSize", pageSize);
        OkGo.<String>post(Content.baseUrl + "link/deviceUseLog/selectUseLogList")
                .upJson(GsonUtils.toJson(hashMap))
                .tag(this)
                .execute(new StringCallback() {
                    @Override
                    public void onSuccess(Response<String> response) {
                        LogUtils.i("lufei", response.body());
//                        tv_accessControl
                        try {
                            AccessControlBean2 accessControlBean2 = GsonUtils.fromJson(response.body(), AccessControlBean2.class);
                            StringBuilder stringBuilder = new StringBuilder();
                            for (AccessControlBean2.RowsDTO row : accessControlBean2.rows) {
                                stringBuilder.append(row.createTime);
                                stringBuilder.append("  ");
                            }
                            tv_accessControl.setText(stringBuilder);
                            LogUtils.i("lufei_jiexi", stringBuilder, "onSuccess");
                        } catch (Exception e) {
                            LogUtils.i("lufei_jiexi", response.body(), e.getMessage());
                            e.printStackTrace();
                        }

                    }
                });
    }

    // getTime()方法
    private String getTime(Date date) {
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        return format.format(date);
    }

    private TimePickerView pvTime;
    SingleDateAndTimePickerDialog.Builder singleBuilder;
    DoubleDateAndTimePickerDialog.Builder doubleBuilder;
    SimpleDateFormat simpleDateFormat;
    private static String TAG = "SingleDatePickerMainActivityWithDoublePicker";
    private void initTime() {
        simpleTimeClicked();

    }
    public void simpleTimeClicked() {

        Calendar calendar = Calendar.getInstance();

        calendar.set(Calendar.HOUR_OF_DAY, 21);
        calendar.set(Calendar.MINUTE, 50);

        final Date defaultDate = calendar.getTime();

        singleBuilder = new SingleDateAndTimePickerDialog.Builder(this)
                .setTimeZone(TimeZone.getDefault())
//                .bottomSheet()
//                .curved()

                .defaultDate(TimeUtils.getNowDate())

                //.titleTextColor(Color.GREEN)
                //.backgroundColor(Color.BLACK)
                //.mainColor(Color.GREEN)
                .displayAmPm(false)
                .displayMinutes(false)
                .displayHours(true)
                .displayDays(true)
//                .displayMonth(true)
                .displayYears(true)

                .displayListener(new SingleDateAndTimePickerDialog.DisplayListener() {
                    @Override
                    public void onDisplayed(SingleDateAndTimePicker picker) {
                        Log.d(TAG, "Dialog displayed");
                    }


                })

                .title("选择时间")
                .listener(new SingleDateAndTimePickerDialog.Listener() {
                    @Override
                    public void onDateSelected(Date date) {
                        ToastUtils.showShort(TimeUtils.date2String(date));
                        String s1x = TimeUtils.date2String(date);
                    }
                });
        singleBuilder.display();
    }
}
